package com.hyt.it.ogt.kq.service.gov.schedule.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BitSetUtils {
    private static final Logger logger = LoggerFactory.getLogger(BitSetUtils.class);

    // 得到bitset为1的序号
    public static int[] convertBitSet2Index(BitSet bitSet) {
        String bitSetStr = bitSet.toString().replace("{", "").replace("}", "").replace(" ", "");
        String[] indesStr = bitSetStr.split(",");
        return Arrays.stream(indesStr).mapToInt(Integer::parseInt).toArray();
    }

    public static List<Integer> andBitSet2Indexs(Integer index, List<BitSet> bitSets) {
        List<Integer> result = new ArrayList<>();
        for (int j = 0; j < bitSets.size(); j++) {
            BitSet bitSetClone = (BitSet) bitSets.get(index).clone();
            BitSet compareBitSet = (BitSet) bitSets.get(j);
            bitSetClone.and(compareBitSet);
            if (bitSetClone.cardinality() == 0 || index == j) {
                result.add(j);
            }
        }
        return result;
    }

    public static List<List<Integer>> andBitSet2Indexs(List<BitSet> bitSets) {
        List<List<Integer>> result = new ArrayList<>(bitSets.size());
        int size = bitSets.size();
        for (int i = 0; i < bitSets.size(); i++) {
            List<Integer> indexs = new ArrayList<>();
            if (i % 1000 == 0) {
                logger.debug("computer bit set current number : {}, total number :{}", i, bitSets.size());
            }
            for (int j = 0; j < size; j++) {
                BitSet bitSetClone = (BitSet) bitSets.get(i).clone();
                BitSet compareBitSet = (BitSet) bitSets.get(j);
                bitSetClone.and(compareBitSet);
                if (bitSetClone.cardinality() == 0 || i == j) {
                    indexs.add(j);
                }
            }
            result.add(indexs);
        }
        return result;
    }

    public static List<BitSet> andBitSets(List<BitSet> bitSets) {
        List<BitSet> result = new ArrayList<>(bitSets.size());
        int size = bitSets.size();
        for (int i = 0; i < bitSets.size(); i++) {
            if (i % 1000 == 0) {
                logger.debug("computer bit set current number : {}, total number :{}", i, bitSets.size());
            }
            BitSet bitSet = new BitSet(size);
            for (int j = 0; j < size; j++) {
                BitSet bitSetClone = (BitSet) bitSets.get(i).clone();
                BitSet compareBitSet = (BitSet) bitSets.get(j);
                bitSetClone.and(compareBitSet);
                if (bitSetClone.cardinality() == 0 || i == j) {
                    bitSet.set(j);
                }
            }
            result.add(bitSet);
        }
        return result;
    }
}
